require('dotenv').config()
const https = require('https');
const fs = require('fs');
const cors = require('cors');
const { expressjwt } = require('express-jwt');
const { Server } = require('socket.io');
const setupSockets = require('./core/socket/index.js');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
   res.send('Hello, HTTPS with Express!');
});
// 加载 SSL 证书
const options = {
   key: fs.readFileSync('./bin/SSL/key.pem'),
   cert: fs.readFileSync('./bin/SSL/cert.pem')
};

const server = https.createServer(options, app);

const io = new Server(server, {
    cors: {
        origin: "*",
    }
});

setupSockets(io);

app.use('/upload', express.static(__dirname + '/upload')) // 设置静态资源目录
app.use(express.urlencoded({ extended: false })) // 解析请求体
app.use(express.json()) // 解析请求体
app.use(cors()) // 允许跨域请求
app.use(expressjwt({
    secret: process.env.SECRET_KEY,
    algorithms: ['HS256'],
}).unless({
    path: [
        '/user/login',
        '/user/register',
        '/user/verify'
    ],
}))

// 引入路由
const usersRouter = require('./router/users.js')
app.use('/user', usersRouter)
const friendshipRouter = require('./router/friendship.js')
app.use('/friend', friendshipRouter)
const groupchatRouter = require('./router/groupchat.js')
app.use('/groupchat', groupchatRouter)
const uploadRouter = require('./router/upload.js')
app.use('/upload', uploadRouter)
const chatRouter = require('./router/chat.js')
app.use('/chat', chatRouter)

// 创建 HTTPS 服务
server.listen(5201, () => {
   console.log('Express HTTPS server is running https://localhost:5201');
});